// src/utils/mqtt.js
import mqtt from "mqtt";

let client = null;

export function connectMQTT({
  host , 
  clientId ,
  username,
  password,
  keepalive = 60,
}) {
  return new Promise((resolve, reject) => {
    client = mqtt.connect(host, {
      clientId,
      username,
      password,
      keepalive,
      reconnectPeriod: 5000, // 自动重连
      clean: true,
    });

    client.on("connect", () => {
      console.log("MQTT 连接成功 ✅");
      resolve(client);
    });

    client.on("error", (err) => {
      console.error("MQTT 连接失败 ❌", err);
      reject(err);
    });

    client.on("reconnect", () => {
      console.log("MQTT 重连中...");
    });

    client.on("close", () => {
      console.log("MQTT 连接已关闭");
    });
  });
}

export function subscribe(topic, qos = 0) {
  if (client) {
    client.subscribe(topic, { qos }, (err) => {
      if (!err) {
        console.log(`订阅成功 -> ${topic}`);
      } else {
        console.error("订阅失败", err);
      }
    });
  }
}

export function publish(topic, message, qos = 0) {
  if (client) {
    client.publish(topic, message, { qos });
    console.log(`发布消息 -> ${topic}: ${message}`);
  }
}

export function onMessage(callback) {
  if (client) {
    client.on("message", (topic, message) => {
      callback(topic, message.toString());
    });
  }
}

export function disconnect() {
  if (client) {
    client.end();
    console.log("MQTT 已断开");
  }
}
